
package com.craterhill.java.ems.service.impl;

import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.AutoPopulatingList;

import com.craterhill.java.ems.common.beans.Classes;
import com.craterhill.java.ems.common.beans.Section;
import com.craterhill.java.ems.dao.ClassesDao;
import com.craterhill.java.ems.dao.SectionDao;
import com.craterhill.java.ems.service.ClassesService;

@Service
public class ClassesServiceImpl implements ClassesService {

	private ClassesDao classesDao;
	private SectionDao sectionDao;

	@Autowired
	public ClassesServiceImpl(final ClassesDao classesDao, final SectionDao sectionDao) {
		this.classesDao = classesDao;
		this.sectionDao = sectionDao;
	}

	@Override
	public Classes saveClass(final Classes classes) {

		clearEmptySections(classes.getSections());

		final int classId = classesDao.save(classes);
		sectionDao.save(classId, classes.getSections());

		classes.setClassesId(classId);
		return classes;
	}

	@Override
	public boolean updateClass(Classes classes) {

		clearEmptySections(classes.getSections());

		classesDao.update(classes);
		sectionDao.remove(classes.getClassesId());
		sectionDao.save(classes.getClassesId(), classes.getSections());
		return false;
	}

	@Override
	public List<Classes> getClasses() {
		return classesDao.findAll();
	}

	@Override
	public Classes getClass(int classId) {
		Classes classes = classesDao.find(classId);
		List<Section> sectionList = sectionDao.findByClasses(classes.getClassesId());
		AutoPopulatingList<Section> autoPopulatingList = new AutoPopulatingList<Section>(sectionList, Section.class);
		classes.setSections(autoPopulatingList);
		return classes;
	}

	public boolean deleteClass(final int classId) {
		classesDao.remove(classId);
		sectionDao.remove(classId);
		return true;
	}

	private void clearEmptySections(final List<Section> sectionList) {
		for(Iterator<Section> it = sectionList.iterator(); it.hasNext();){
			Section section = it.next();
			if(section.getSectionName() == null || section.getSectionName().length() == 0){
				it.remove();
			}
		}
	}
}
